package com.ohs.ohsoa.system.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.github.pagehelper.PageInfo;
import com.ohs.ohsoa.system.dto.PasswordDto;
import com.ohs.ohsoa.system.entity.UserInfo;
import com.ohs.ohsoa.system.service.UserInfoService;
import com.ohs.ohsoa.system.vo.DepartmentAndRoleVo;
import com.ohs.ohsoa.system.vo.LoginInfoVo;
import com.ohs.ohsoa.system.vo.UserInfoVo;
import com.ohs.ohsoa.utils.auth.UserLoginToken;
import com.ohs.ohsoa.utils.bean.requestBean.PageParam;
import com.ohs.ohsoa.utils.bean.responseBean.ResultBean;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 用户信息controller
 *
 * @author mwx
 * @since 2021年10月08日
 */
@Api(value = "用户信息controller", tags = "用戶信息")
@RestController
@RequestMapping("/userInfo")
public class UserInfoController {

    @Resource
    private UserInfoService userInfoService;

    /**
     * 用户登录
     *
     * @author mwx
     * @since  2021年10月08日
     * @param userInfo 用户信息数据
     * @return 实例对象
     */
    @PostMapping("login")
    @ApiOperation(httpMethod = "POST", value = "登录")
    public ResultBean<LoginInfoVo> login(@RequestHeader(value="token",required = false) String token,  @RequestBody UserInfo userInfo, HttpServletResponse rep) {
    	if(token!=null) {
    		UserInfoVo userInfoVo = userInfoService.getUserInfo();
            if (userInfoVo == null) {
            	rep.setStatus(401);
                throw new RuntimeException("トークンが存在しないですが、ご再度ログインしてください。");
            }
            // 验证 token
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(userInfoVo.getPwd())).build();
            try {
                jwtVerifier.verify(token);
            } catch (JWTVerificationException e) {
            	rep.setStatus(401);
                throw new RuntimeException("トークンの期限が切れましたが、ご再度ログインしてください。");
            }
            userInfo.setUserNo(userInfoVo.getUserNo());
            userInfo.setPwd(userInfoVo.getPwd());
    	}
    	
        LoginInfoVo loginInfoVo = userInfoService.login(userInfo.getUserNo(), userInfo.getPwd());
        return ResultBean.success(loginInfoVo);
    }

    /**
     * 用户分页查询
     *
     * @author mwx
     * @since 2021年10月08日
     * @param pageParam 检索用参数
     * @return 实例对象
     */
    @UserLoginToken
    @PostMapping(value = "/listUserInfo")
    @ApiOperation(httpMethod = "POST", value = "获取用户列表信息")
    public ResultBean<PageInfo<UserInfoVo>> listSubgroup(@RequestBody PageParam<UserInfo> pageParam) {
        List<UserInfoVo> listSubgroup = userInfoService.listUserInfo(pageParam);
        return ResultBean.success(new PageInfo<>(listSubgroup));
    }

    /**
     * 根据id查询
     *
     * @author mwx
     * @since 2021年10月8日
     * @param  user ’id‘
     * @return 实例对象
     */
    @UserLoginToken
    @PostMapping(value = "/getUserById")
    @ApiOperation(httpMethod = "POST", value = "根据id获取用户详细信息")
    public ResultBean<?> queryById(@RequestBody @ApiParam(name = "") UserInfo user) {
        UserInfoVo userInfo = userInfoService.getUserById(user.getUserinfoGuid());
        return ResultBean.success(userInfo);
    }

    /**
     * 新增
     *
     * @author mwx
     * @since 2021年10月8日
     * @param user ’id‘
     * @return 实例对象
     */
    @UserLoginToken
    @PostMapping(value = "/insert")
    @ApiOperation(httpMethod = "POST", value = "新增用户")
    public ResultBean<?> insertUser(@RequestBody @Valid UserInfo user,BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultBean.fail(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        userInfoService.insert(user);
        return ResultBean.success();
    }

    /**
     * 修改
     *
     * @author mwx
     * @since 2021年10月8日
     * @param  user ’id‘
     * @return 实例对象
     */
    @UserLoginToken
    @PostMapping(value = "/update")
    @ApiOperation(httpMethod = "POST", value = "修改用户")
    public ResultBean<?> updateUser(@RequestBody @ApiParam(name = "") @Valid UserInfo user,BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultBean.fail(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        userInfoService.update(user);
        return ResultBean.success();
    }

    /**
     * 批量删除
     *
     * @author mwx
     * @since 2021年10月12日
     * @param userInfo ’id‘
     * @return 1为成功
     */
    @UserLoginToken
    @DeleteMapping(value = "/deleteById")
    @ApiOperation(httpMethod = "DELETE", value = "批量删除")
    public ResultBean<?> deleteById(@RequestBody UserInfo userInfo) {
        List<String> ids = userInfo.getIds();
        userInfoService.deleteUserInfoById(ids);
        return ResultBean.success();
    }

    /**
     * 初始化密码
     *
     * @param userInfo id
     * @return 初始化结果
     */
    @UserLoginToken
    @PostMapping(value = "/resetpassword")
    @ApiOperation(httpMethod = "POST", value = "初始化密码")
    public ResultBean<Boolean> resetpassword(@RequestBody UserInfo userInfo) {
        return ResultBean.success(userInfoService.resetpassword(userInfo));
    }

    /**
     * 员工新增时获取所有企业的部门，职务，学历 企业，部门，职务，学历
     ** @return 所有企业的部门，职务，学历 企业，部门，职务，学历
     */
    @UserLoginToken
    @PostMapping(value = "/insert/info")
    @ApiOperation(httpMethod = "POST", value = "员工新增时获取所有企业的部门，职务，学历")
    public ResultBean<DepartmentAndRoleVo> departmentAndRoleByEnterprises() {
        return ResultBean.success(userInfoService.departmentAndRoleByEnterprises());
    }

    /**
     * 修改权限
     *
     * @param userInfo 用户数据
     * @return 修改结果
     */
//    @UserLoginToken
//    @PostMapping(value = "/update/authority")
//    @ApiOperation(httpMethod = "POST", value = "修改权限")
//    public ResultBean<Boolean> selectAuthority(@RequestBody @Valid  UserInfo userInfo, BindingResult bindingResult) {
//        if (bindingResult.hasErrors()) {
//            return ResultBean.fail(bindingResult.getAllErrors().get(0).getDefaultMessage());
//        }
//        return ResultBean.success(userInfoService.selectAuthority(userInfo));
//    }
//    @PostMapping(value = "/update/authority")
//    @ApiOperation(httpMethod = "POST", value = "修改权限")
//    public ResultBean<Boolean> selectAuthority(@RequestBody @Valid  UserInfo userInfo, BindingResult bindingResult) {
//        if (bindingResult.hasErrors()) {
//            return ResultBean.fail(bindingResult.getAllErrors().get(0).getDefaultMessage());
//        }
//        return ResultBean.success(userInfoService.selectAuthority(userInfo));
//    }

    /**
     * 修改密码
     *
     * @param passwordDto 用户密码数据
     * @return 修改结果
     */
    @UserLoginToken
    @PostMapping(value = "/update/password")
    @ApiOperation(httpMethod = "POST", value = "修改密码")
    public ResultBean<Boolean> updatePassword(@RequestBody @Valid PasswordDto passwordDto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultBean.fail(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }
        return ResultBean.success(userInfoService.updatePassword(passwordDto));
    }
}
